Ext.onReady(function(){
	var isModify = false;
	Ext.define("ComUser",{
	   extend:'Ext.data.Model',
	   fields:['userid','username', 'uname', 'gender','birthDate','address','organization.orgid','organization.orgname','isvalid']
	});
	var store = Ext.create('Ext.data.Store', {
		pageSize:Ext.app.Config.DEFAULT_PAGE_SIZE,
        storeId:'simpsonsStore',
        model:'ComUser',
        proxy: {
            type: 'ajax',
            url:contextPath+'/auth/allusers',
            //用于将store的默认get提交方式改成post
            actionMethods: {  
                read: 'POST'  
            },
            reader: {
                type: 'json',
                root: 'users',
                totalProperty:'totalPageCount'//defaults:total
            }
        }
    });
    var comboTreeStore = Ext.create('Ext.data.TreeStore', {
        proxy:{
            type: 'ajax',
            actionMethods: {  
                read: 'POST'  
            },
            reader: {
                type: 'json'
            },
            url:contextPath+'/auth/allorgs'
        }
    });
    var loadMask = new Ext.LoadMask(Ext.getBody(),{
       msg:'正在加载数据...'
    });
    //loadMask.show();
	var grid = Ext.create('Ext.grid.Panel', {
		id:'gridPanel',
		region:'center',
        store: store,
        viewConfig:{
            loadingText:'正在加载数据...'
        },
        selType:'checkboxmodel',  //rowmodel,cellmodel
        simpleSelect: true,    //简单选择功能开启 
        multiSelect: true,       // 启用多行选择 
        enableKeyNav: true,     //启用键盘导航 
        columns: [ 
        Ext.create('Ext.grid.RowNumberer', {
        	text: '行号', 
        	width: 40,
        	align:'center' 
        }),{ 
            text:'ID',
            dataIndex:'userid',
            hidden:true
        },{
        	text: '用户名',
        	dataIndex: 'username'
        },{ 
            text: '姓名', 
            dataIndex: 'uname'
        },{ 
            text: '性别', 
            dataIndex: 'gender',
            renderer:function(v){
                switch(v){
                    case "F" : return '<span class="sx-icon-user_female" title="女">&nbsp;&nbsp;&nbsp;&nbsp;</span>';
              	  	case 'M' : return '<span class="sx-icon-user" title="男">&nbsp;&nbsp;&nbsp;&nbsp;</span>';
                    default  : return '未知';
              	}
            },
            align:'center' 
        },{
        	text: '生日', 
            dataIndex: 'birthDate',
            align:'center'
        },{
        	text: '地址', 
        	dataIndex: 'address' 
        },{
        	text: '所属机构', 
        	dataIndex: 'organization.orgname' 
        },{
            text: '状态', 
            dataIndex: 'isvalid',
            renderer:function(v){
                return v=='1'?'有效':'无效'
            },
            align:'center' 
        }],
        layout:'fit',
        forceFit:true,
        stripRows: true,
        columnLines:true,
        frame:true,
        renderTo: Ext.getBody(),
        dockedItems: [{
            xtype:'toolbar',
            dock:'top',
            items:[{
            	id:'tbar_add_btn',
                text:'添加',
                iconCls:'sx-icon-user_add',
                handler:function(){
                	isModify = false;
                	Ext.getCmp("userForm").getForm().reset();
                	win.show();
                }
            },"-",{
                id:'tbar_edit_btn',
                text:'修改',
                iconCls:'sx-icon-user_edit',
                handler:function(){
                	isModify = true;
                    var rows = grid.getSelectionModel().getSelection();
                    if(rows.length != 1){
                        top.Ext.Msg.alert("提示","请选择一条记录!");
                        return false;
                    }
                    Ext.getCmp("userForm").getForm().reset();
                    Ext.getCmp("userForm").loadRecord(rows[0]);
                    Ext.getCmp("organization.orgid").setDefaultValue(rows[0].get("organization.orgid"),rows[0].get("organization.orgname"));
                    //Ext.getCmp("organization.orgid").setPathValue('/root/'+rows[0].get("organization.orgid"));
                    Ext.app.Config.initRadioGroup(Ext.getCmp("gender"),rows[0].get("gender"));
                    Ext.app.Config.initRadioGroup(Ext.getCmp("isvalid"),rows[0].get("isvalid"));
                    win.show();
                }
            },"-",{
                id:'tbar_del_btn',
                text:'删除',
                iconCls:'sx-icon-user_delete',
                handler:function(){
                    var rows = grid.getSelectionModel().getSelection();
                    if(rows.length == 0){
                        top.Ext.Msg.alert("提示","请选择记录!");
                        return false;
                    }	
                    top.Ext.Msg.confirm({
                        title:"提示",
                        msg:"确认删除所选记录吗？",
                        icon:Ext.Msg.QUESTION,
                        buttons: Ext.Msg.YESNO,
                        callback:function(key){
                            if(key != "yes")
                            	return false;
                        	Ext.Ajax.request({
                                url:contextPath + "/auth/deluser",
                                method:'POST',
                                params:{
                                    userid:(function(){
                                        var ids=[];
                                        for(var i = 0; i < rows.length; i++){
                                            ids.push(rows[i].get("userid"));
                                        }
                                        return ids.join(",");
                                    })()
                                },
                                success:function(response,options){
                                    store.reload();                            
                                    var result = Ext.JSON.decode(response.responseText);
                                    Ext.Msg.showParentNotify({title:'提示', msg:result.message}); 
                                },
                                failure:function(response,options){
                                    var result = Ext.JSON.decode(response.responseText);
                                    Ext.Msg.showParentNotify({title:'提示', msg:result.message}); 
                                }
                            });   
                        }
                    });
                }
            },'->',"-",{
                id:'tbar_cbtree_orgid',
                emptyText:'机构',
                fieldLabel:'',
                xtype:'combotree',
                editable: false,
                multiCascade:false,
                multiSelect : false,
                store:comboTreeStore
            },"-",{
                id:'tbar_txt_username',
                xtype:'textfield',
                emptyText:'用户名'
            },"-",{
            	id:'tbar_txt_uname',
                xtype:'textfield',
                emptyText:'姓名'
            },"-",{
                text:'查询',
                iconCls:'sx-icon-magnifier',
                handler:function(){
                    store.load({
                        params:{
                           username:Ext.getCmp("tbar_txt_username").getValue(),
                           uname:Ext.getCmp("tbar_txt_uname").getValue(),
                           'organization.orgid':Ext.getCmp("tbar_cbtree_orgid").getSubmitValue()
                        }
                    });             
                }
            },"-",{
                text:'重置',
                iconCls:'sx-icon-arrow_redo',
                handler:function(){
                    Ext.getCmp("tbar_txt_username").setValue("");             
                    Ext.getCmp("tbar_txt_uname").setValue("");             
                    Ext.getCmp("tbar_cbtree_orgid").clearValue(); 
                }
            }]
        },{
            xtype: 'pagingtoolbar',
            store: store,
            dock: 'bottom',
            displayInfo: true
        }]
    });
    store.on("beforeload",function (store, options) {
        var params = {
            username:Ext.getCmp("tbar_txt_username").getValue(),
            uname:Ext.getCmp("tbar_txt_uname").getValue(),
            'organization.orgid':Ext.getCmp("tbar_cbtree_orgid").getSubmitValue()
        };
        Ext.apply(store.proxy.extraParams,params);//*核心代码
    });
    store.on("load",function(){
        //loadMask.hide();        
    });
	store.load({
	    limit:Ext.app.Config.DEFAULT_PAGE_SIZE,
	    start:0
	});
    Ext.create("Ext.container.Viewport",{
        layout:'border',
        renderTo:Ext.getBody(),
        items:[grid]
    });
    
    var win = Ext.create("Ext.window.Window",{
        title:'用户信息',
        layout:'fit',
        modal:true,
        width:310,
        height:275,
        resizable:false,
        closable:true,
        closeAction:"close",
        animateTarget:Ext.getBody(),
        buttonAlign:'center',
        bodyStyle:'padding:5px',
        items:[{
            xtype:'form',
            id:'userForm',
            border:false,
            frame:true,
            bodyStyle:'margin-top:0px;',
            defaultType:'textfield',
            defaults:{
                autoScroll: true,
                width:250
            },
            fieldDefaults: {
                labelAlign: 'right',
                labelWidth: 70,
                labelSeparator:':',
                maxLength:20,
                allowBlank:false
            },
            items:[{
                id:'userid',
                hidden:true,
                name:'userid',
                allowBlank:true
            },{
            	id:'username',
                fieldLabel:'用户名',
                name:'username'
            },{
                id:'uname',
                fieldLabel:'姓名',
                name:'uname'
            },{
                id:'gender',
                xtype:'radiogroup',
                fieldLabel:'性别',
                items: [
                    { boxLabel: '男', name: 'gender', inputValue: 'M',checked:true},
                    { boxLabel: '女', name: 'gender', inputValue: 'F'},
                    { boxLabel: '未知', name: 'gender', inputValue: 'U'}
                ]
            },{
                id:'birthDate',
                xtype:'datefield',
                fieldLabel:'生日',
                name:'birthDate',
                format:'Y-m-d'
            },{
                id:'address',
                fieldLabel:'地址',
                name:'address'
            },{
                id:'isvalid', 
                xtype: 'radiogroup',
                fieldLabel:'是否有效',
                items:[
                    { boxLabel: '有效', name: 'isvalid', inputValue: '1',checked:true},
                    { boxLabel: '无效', name: 'isvalid', inputValue: '0'}
                ]
            },{
                id:'organization.orgid',
                fieldLabel:'所属机构',
                name:'organization.orgid',
                xtype:'combotree',
                editable: false,
                multiCascade:false,
                multiSelect : false,
                store:comboTreeStore
            }]
        }],
        buttons:[{
            text:'确定',
            iconCls:'sx-icon-accept',
            handler:function(){
                var f = Ext.getCmp("userForm").getForm();
                if(f.isValid()){
                    f.submit({
                        clientValidation: true,
                        method:'POST',
                        url: contextPath + "/auth/addUser",
                        success: function(form, action) {
                            var result = action.result;  
                            if(!isModify){
                                top.Ext.Msg.confirm("提示",result.message+",是否继续添加用户？",function(v){
                                    if(v != "yes"){
                                    	win.close();
                                        store.reload();
                                    }else{
                                    	f.reset();
                                    }
                                });                            
                            }else{
                            	win.close();
                                store.reload();
                                Ext.Msg.showParentNotify({title:'提示', msg:result.message}); 
                            }
                            
                        },
                        failure: function(form, action) {
                            var result = action.result;
                            Ext.Msg.showParentNotify({title:'提示', msg:result.message}); 
                        }
                    });
                }
            }
        },{
            text:'重置',
            iconCls:'sx-icon-arrow_redo',
            handler:function(){
                Ext.getCmp("userForm").getForm().reset();
            }
        },{
            text:'取消',
            iconCls:'sx-icon-cancel',
            handler:function(){
                win.close();
            }
        }]
    });
});
